//
//  MusicPlayViewController.m
//  ToWhere
//
//  Created by dllo on 15/11/22.
//  Copyright © 2015年 www.TE.com. All rights reserved.
//

#import "MusicPlayViewController.h"
#import <UIImageView+WebCache.h>
#import <SDWebImageManager.h>
#import "MusicPlayerTableViewCell.h"
#import <STKAudioPlayer.h>
#import "MusicPlayModelTableViewCell.h"
#import "MusicCollection.h"
#import "CoreDatamanager.h"
#import "MusicDetailModel.h"
#import "Voice.h"
#import "UMSocial.h"

typedef enum
{
    OrderModel = 1,
    randomModel,
    OneSongMode ,
}Model;

@interface MusicPlayViewController ()<UITableViewDataSource, UITableViewDelegate,STKAudioPlayerDelegate>

@property(nonatomic, retain) UITableView *tableView;

@property(nonatomic, retain) UITableView *playTableView;

@property(nonatomic, retain) UITableView *collectTableView;

@property(nonatomic, retain) STKAudioPlayer *player;

@property(nonatomic, retain) NSArray *modelArray; //播放模式文字

@property(nonatomic, retain) NSArray *imageArray; //播放模式图片

@property(nonatomic, retain) UIImageView *image; //动画

@property(nonatomic, retain) UIImageView *imageview; //背景图片

@property(nonatomic, assign) NSInteger playModel; //播放模式

@property(nonatomic, retain) UISlider *progressSlider; //时间进度条

@property(nonatomic, retain) UISlider *voice; //时间进度条

@property(nonatomic, retain) NSTimer *timer;

@property(nonatomic, retain) UIView *playListView;

@property(nonatomic, retain) CoreDatamanager *coreDataManager;

@property(nonatomic, retain) NSArray *collectArray;

@end

@implementation MusicPlayViewController

- (void)dealloc
{
    [_backImage release];
    [_playListArray release];
    [_tableView release];
    [_playTableView release];
    [_collectTableView release];
    [_modelArray release];
    [_player release];
    [_imageArray release];
    [_image release];
    [_imageview release];
    [_progressSlider release];
    [_timer release];
    [_playListView release];
    [_voice release];
    [_coreDataManager release];
    [_collectArray release];
    [super dealloc];
}

+(MusicPlayViewController *)shareMusicPlayViewController
{
    static MusicPlayViewController *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[MusicPlayViewController alloc]init];
    });
    return player;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.coreDataManager = [CoreDatamanager shareManager];
//    NSLog(@"%@", [self.coreDataManager applicationDocumentsDirectory]);
    self.modelArray = @[@"顺序播放",@"随机播放", @"单曲循环"];
    self.imageArray = @[@"Music_shunxu", @"Music_suiji", @"Music_danqu"];
    self.collectArray = [NSArray array];
    self.playModel = 1;
    self.collectArray = @[@"collec", @"fenxiang", @"Music_caidan"];    
    
    //创建标题
    [self createTitle];
    
    //布置页面
    [self createView];
    
    //创建tableView
    [self createTableView];
    
    //创建播放模式页面
    [self createPlayView];
}

-(void)viewWillAppear:(BOOL)animated
{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MusicCollection"];
    NSArray *collecArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    for (MusicCollection *model in collecArray) {
            if ([[model musicID] isEqual:[self.playListArray[self.row] ID]]) {
                
                UIButton *collect = (UIButton *)[self.view viewWithTag:5000];
                [collect setBackgroundImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
                break;
            }
            else
            {
                UIButton *collect = (UIButton *)[self.view viewWithTag:5000];
                [collect setBackgroundImage:[UIImage imageNamed:@"collec"] forState:UIControlStateNormal];
            }
        }
    if (self.player.state == STKAudioPlayerStatePlaying) {
        [self animationDidStart];
        [self animationResume];
        [self changeViewWhenSongChange:self.row];
    }
}

-(void)setPlayListArray:(NSArray *)playListArray
{
    if (_playListArray != playListArray) {
        [_playListArray release];
        _playListArray = [playListArray retain];
    }
    [self.tableView reloadData];
    [self playMusic];
    [self changeViewWhenSongChange:self.row];
}

-(void)setRow:(NSInteger)row
{
    if (_row != row) {
        _row = row;
       [self playMusic];
    }
}

#pragma mark 播放音乐
-(void)playMusic
{
    [self.player play:[self.playListArray[self.row] source]];
    [self changeViewWhenSongChange:self.row];
    //timer定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(time) userInfo:nil repeats:YES];
}

#pragma mark 创建标题
-(void)createTitle
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.imageview = [[UIImageView alloc]initWithFrame:self.view.frame];
    [self.imageview sd_setImageWithURL:[NSURL URLWithString:self.backImage] placeholderImage:[UIImage imageNamed:@"placeHoder"]];
    [self.view addSubview:self.imageview];
    [_imageview release];
    
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    effectView.frame = self.imageview.bounds;
    effectView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.1];
    [self.imageview addSubview:effectView];
    [effectView release];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(15 * kWidth, 25 * kHeight, 20 * kWidth, 20 * kHeight);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"Food_back"] forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    [backBtn addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *songName = [[UILabel alloc]initWithFrame:CGRectMake(45 * kWidth, 25 * kHeight, 320 * kWidth, 20 * kHeight)];
    songName.textColor = [UIColor whiteColor];
    songName.font = [UIFont systemFontOfSize:19 * kWidth];
    songName.text =  [self.playListArray[self.row] name];
    songName.tag = 55555;
    [self.view addSubview:songName];
    [songName release];
    
    UILabel *singerName = [[UILabel alloc]initWithFrame:CGRectMake(45 * kWidth, 55 * kHeight, 150 * kWidth, 20 * kHeight)];
    singerName.textColor = [UIColor whiteColor];
    singerName.font = [UIFont systemFontOfSize:16 * kWidth];
    singerName.text = [[self.playListArray[self.row] User]objectForKey:@"name"];
    singerName.tag = 66666;
    [self.view addSubview:singerName];
    [singerName release];

}
-(void)BackAction:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 创建页面
-(void)createView
{
    self.player = [[STKAudioPlayer alloc]initWithOptions:(STKAudioPlayerOptions){
        .flushQueueOnSeek = YES,
        .enableVolumeMixer = YES
    }];
    self.player.delegate = self;
    
    //播放音乐
    [self playMusic];
    
    [_player release];
    
    self.image = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 70 * kWidth, 140 * kHeight, 140 * kWidth, 140 * kWidth)];
    [self.image sd_setImageWithURL:[NSURL URLWithString:self.backImage] placeholderImage:[UIImage imageNamed:@"placeHoder"]];
    self.image.layer.masksToBounds = YES;
    self.image.layer.cornerRadius = 140 / 2 * kWidth;
    [self.view addSubview:self.image];
    [_image release];
    
    [self animationDidStart];
    [self viewWillAppear:YES];
    for (int i = 0; i < 3; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(120 * kWidth + i * 60 * kWidth, 385 * kHeight, 25 * kWidth, 25 * kHeight);
        [btn setBackgroundImage:[UIImage imageNamed:self.collectArray[i]] forState:UIControlStateNormal];
        [self.view addSubview:btn];
        btn.tag = 5000 + i;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    }

    //播放进度条
    self.progressSlider = [[UISlider alloc]initWithFrame:CGRectMake(20 * kWidth, 440 * kHeight, self.view.frame.size.width - 40 * kWidth, 10 * kHeight)];
    [self.progressSlider addTarget:self action:@selector(progressSliderAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_progressSlider];
    [_progressSlider setThumbImage:[UIImage imageNamed:@"Slider"] forState:UIControlStateNormal];
    [_progressSlider setThumbImage:[UIImage imageNamed:@"Slider"] forState:UIControlStateHighlighted];
    [_progressSlider release];
    
    for (int i = 0; i < 2; i++) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20 * kWidth + i * (self.view.frame.size.width - 80 * kWidth), 460 * kHeight, 50 * kWidth, 20 * kHeight)];
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:15 * kWidth];
        label.tag = 99999 + i;
        [self.view addSubview:label];
        [label release];
    }

    NSArray *playArray = @[@"Music_shunxu", @"Music_shangyishou",@"Music_kaishi", @"Music_next", @"Music_liebiao"];
    for (int i = 0; i < playArray.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:[UIImage imageNamed:playArray[i]] forState:UIControlStateNormal];
        if (i == 2) {
            btn.frame = CGRectMake(30 * kWidth + i * 67 * kWidth, 520 * kHeight, 45 * kWidth , 45 * kHeight );
        }
        else
        {
            btn.frame = CGRectMake(30 * kWidth + i * 70 * kWidth , 530 * kHeight, 30 * kWidth , 30 * kHeight );
        }
        btn.tag = 9000 + i;
        [self.view addSubview:btn];
        [btn addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    }
}
//分享等按钮的点击事件
-(void)btnAction:(UIButton *)btn
{
    if (btn.tag == 5000) {
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MusicCollection"];
        NSArray *collecArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
        if (collecArray.count == 0) {
            MusicCollection *collect = [NSEntityDescription insertNewObjectForEntityForName:@"MusicCollection" inManagedObjectContext:_coreDataManager.managedObjectContext];
            collect.musicID = [self.playListArray[self.row] ID];
            collect.name = [self.playListArray[self.row] name];
            collect.source = [self.playListArray[self.row] source];
            collect.pic_750 = [self.playListArray[self.row] pic_750];
            collect.user = [[self.playListArray[self.row] User] objectForKey:@"name"];
            [_coreDataManager saveContext];
            [btn setBackgroundImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
        }
        else
        {
            BOOL result = NO;
            int index = 0;
            for (int i = 0; i < collecArray.count; i++) {
                if ([[collecArray[i] musicID] isEqual:[self.playListArray[self.row] ID]]) {
                    result = YES;
                    index = i;
                   
                }
            }
            if (result) {
                [_coreDataManager.managedObjectContext deleteObject:collecArray[index]];
                [_coreDataManager saveContext];
                [btn setBackgroundImage:[UIImage imageNamed:@"collec"] forState:UIControlStateNormal];
            }
            else
                {
                    MusicCollection *collect = [NSEntityDescription insertNewObjectForEntityForName:@"MusicCollection" inManagedObjectContext:_coreDataManager.managedObjectContext];
                    collect.musicID = [self.playListArray[self.row] ID];
                    collect.name = [self.playListArray[self.row] name];
                    collect.source = [self.playListArray[self.row] source];
                    collect.pic_750 = [self.playListArray[self.row] pic_750];
                    collect.user = [[self.playListArray[self.row] User] objectForKey:@"name"];
                    [_coreDataManager saveContext];
                    [btn setBackgroundImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
                }


        }
        [request release];
    }
    else if (btn.tag == 5001)
    {
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"5655ae58e0f55a464d000a1c"
                                          shareText:[self.playListArray[self.row] name]
                                         shareImage:[UIImage imageNamed:@"icon.png"]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                           delegate:nil];

    }
    else
    {
        [self createPlayListView];
    }
}

#pragma mark 菜单列表
-(void)createPlayListView
{
    self.playListView = [[UIView alloc]initWithFrame:self.view.frame];
    self.playListView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0];
    [self.view addSubview:self.playListView];
    [_playListView release];
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    effectView.frame = self.imageview.bounds;
    effectView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0];
    [self.playListView addSubview:effectView];
    [effectView release];
    
    UIButton *collect = [UIButton buttonWithType:UIButtonTypeCustom];
    [collect setTitle:@"音旅收藏" forState:UIControlStateNormal];
    collect.frame = CGRectMake( self.view.frame.size.width / 2 - 60 * kWidth, self.view.frame.size.height / 2 - 40 * kHeight, 120 * kWidth, 40 * kHeight);
    collect.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.1];
    [self.playListView addSubview:collect];
    [collect addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //声音进度条
    self.voice = [[UISlider alloc]initWithFrame:CGRectMake(20 * kWidth, 400 * kHeight, self.view.frame.size.width - 50 * kWidth, 10 * kHeight)];
    [self.voice addTarget:self action:@selector(voiceAction:) forControlEvents:UIControlEventValueChanged];
    [self.playListView addSubview:_voice];
    self.voice.minimumValue = 20;
    self.voice.maximumValue = 50;
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Voice"];
    NSArray *collecArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    if (collecArray.count == 0) {
        self.voice.value = self.player.volume;
    }
    else
    {
        self.voice.value = [[collecArray.firstObject voice] floatValue];
    }
    [_voice setThumbImage:[UIImage imageNamed:@"Slider"] forState:UIControlStateNormal];
    [_voice setThumbImage:[UIImage imageNamed:@"Slider"] forState:UIControlStateHighlighted];
    [_voice release];
    
    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Music_voice"]];
    image.frame = CGRectMake(self.view.frame.size.width - 30 * kWidth, 400 * kHeight, 30 * kWidth, 30 * kHeight);
    [self.playListView addSubview:image];
    [image release];
    
}

#pragma mark 收藏
-(void)collectAction:(UIButton *)btn
{
    [UIView animateWithDuration:0.2 animations:^{
        [self createCollectTabelView];
    }];
}

#pragma mark 收藏tableView
-(void)createCollectTabelView
{
    self.collectTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 350 * kHeight, self.view.frame.size.width, 350 * kHeight) style:UITableViewStylePlain];
    self.collectTableView.delegate = self;
    self.collectTableView.dataSource = self;
    self.collectTableView.backgroundColor = [UIColor colorWithRed:0.953 green:0.952 blue:0.973 alpha:1.000];
    [self.view addSubview:self.collectTableView];
    [_collectTableView release];
    
    [self.collectTableView registerClass:[MusicPlayerTableViewCell class] forCellReuseIdentifier:@"MusicPlayerTableViewCell"];
    
}

//声音点击事件
-(void)voiceAction:(UISlider *)slider
{
   self.player.volume = slider.value;
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Voice"];
    NSArray *collecArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    if (collecArray.count != 0) {
        [self.coreDataManager.managedObjectContext deleteObject:collecArray.firstObject];
    }  
    
    Voice *voice = [NSEntityDescription insertNewObjectForEntityForName:@"Voice" inManagedObjectContext:_coreDataManager.managedObjectContext];
    voice.voice = [NSNumber numberWithFloat:slider.value];
    [_coreDataManager saveContext];
    
    [request release];
}
//播放按钮的点击事件
-(void)playAction:(UIButton *)btn
{
    //播放模式
   if(btn.tag == 9000)
    {
        [UIView animateWithDuration:0.2 animations:^{
            self.playTableView.frame = CGRectMake(10 * kWidth, self.view.frame.size.height - 270 * kHeight, 120 * kWidth, 120 * kHeight);
        }];
    }
    else if(btn.tag == 9001) //上一曲
    {
        if (self.playModel == OrderModel) {
            if (self.row == 0) {
                self.row = 0;
            }
            else
            {
                self.row--;
            }
            [self.player play:[self.playListArray[self.row] source]];
            
        }
        if (self.playModel == randomModel) {
            self.row = arc4random() % self.playListArray.count;
            [self.player play:[self.playListArray[self.row] source]];

        }
        if (self.playModel == OneSongMode) {
            [self.player play:[self.playListArray[self.row] source]];
        }
        [self changeViewWhenSongChange:self.row];
        [self viewWillAppear:YES];

    }
    else if (btn.tag == 9002) //播放暂停
    {
        //暂停
        if (self.player.state == STKAudioPlayerStatePaused) {
            [btn setBackgroundImage:[UIImage imageNamed:@"Music_kaishi"] forState:UIControlStateNormal];
            //继续播放
            [self.player resume];
            [self animationDidStart];
            [self animationResume];
            
            //当前是播放状态
        }else if (self.player.state == STKAudioPlayerStatePlaying){
            
            [btn setBackgroundImage:[UIImage imageNamed:@"Music_zanting"] forState:UIControlStateNormal];
             [self.player pause];
             [self animationStop];
            //其他
        }else{
            [self playMusic];
            [btn setBackgroundImage:[UIImage imageNamed:@"Music_kaishi "] forState:UIControlStateNormal];
        }
    }
    else if (btn.tag == 9003) // 下一曲
    {
        
        if (self.playModel == OrderModel) {
            
            if (self.row == self.playListArray.count - 1) {
                self.row = 0;
            }
            else
            {
              self.row++;
            }
            [self.player play:[self.playListArray[self.row] source]];
            
        }
        if (self.playModel == randomModel) {
            self.row = arc4random() % self.playListArray.count;
            [self.player play:[self.playListArray[self.row] source]];
        }
        if (self.playModel == OneSongMode) {
            [self.player play:[self.playListArray[self.row] source]];
        }
        [self viewWillAppear:YES];
        [self changeViewWhenSongChange:self.row];
    }
    else
    {
        [UIView animateWithDuration:0.2 animations:^{
            self.tableView.frame = CGRectMake(0, self.view.frame.size.height - 350 * kHeight, self.view.frame.size.width, 350 * kHeight);
        }];
    }
}

#pragma mark 创建tableView
-(void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 350 * kHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor colorWithRed:0.953 green:0.952 blue:0.973 alpha:1.000];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    [self.tableView registerClass:[MusicPlayerTableViewCell class] forCellReuseIdentifier:@"MusicPlayerTableViewCell"];
}

//返回行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.tableView]) {
        return self.playListArray.count;
    }
    else if ([tableView isEqual:self.playTableView])
    {
        return self.modelArray.count;
    }
    else
    {
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MusicCollection"];
        NSArray *collecArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
        return collecArray.count;
    }
}

//返回分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//返回头视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if ([tableView isEqual:self.tableView]) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 5 * kHeight, self.view.frame.size.width, 20 * kHeight)];
        label.text = @"  播放列表";
        label.backgroundColor = [UIColor colorWithRed:0.953 green:0.952 blue:0.973 alpha:1.000];
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:15 * kWidth];
        return [label autorelease];
    }
    else if([tableView isEqual:self.playTableView])
    {
        return nil;
    }
    else
    {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 5 * kHeight, self.view.frame.size.width, 20 * kHeight)];
        label.text = @"  收藏列表";
        label.backgroundColor = [UIColor colorWithRed:0.918 green:0.917 blue:0.937 alpha:1.000];
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:15 * kWidth];
        return [label autorelease];
    }
}

//返回头视图高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ([self.tableView isEqual:tableView] || [tableView isEqual:self.collectTableView]) {
       return 40 * kHeight;
    }
    else
    {
        return 1;
    }
}

//返回尾视图高
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

//返回行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.tableView] || [tableView isEqual:self.collectTableView]) {
        return 55 * kHeight;
    }
    else
    {
      return 40 * kHeight;
    }
}

//重用池
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.tableView]) {
        MusicPlayerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MusicPlayerTableViewCell" forIndexPath:indexPath];
        cell.musicDetailModel = self.playListArray[indexPath.row];
        cell.row = indexPath.row;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if([tableView isEqual:self.playTableView])
    {
        MusicPlayModelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MusicPlayModelTableViewCell" forIndexPath:indexPath];
        cell.image = self.imageArray[indexPath.row];
        cell.model = self.modelArray[indexPath.row];
        cell.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
        return cell;
    }
    else
    {
        MusicPlayerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MusicPlayerTableViewCell" forIndexPath:indexPath];
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MusicCollection"];
        NSArray *collecArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
        cell.musicDetailModel = collecArray[indexPath.row];
        cell.row = indexPath.row;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [request release];
        return cell;
    }
}

//播放列表点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.tableView]) {
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MusicCollection"];
        NSArray *collecArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
        for (MusicCollection *model in collecArray) {
            if ([[model musicID] isEqual:[self.playListArray[indexPath.row] ID]]) {
                
                UIButton *collect = (UIButton *)[self.view viewWithTag:5000];
                [collect setBackgroundImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
                break;
            }
            else
            {
                UIButton *collect = (UIButton *)[self.view viewWithTag:5000];
                [collect setBackgroundImage:[UIImage imageNamed:@"collec"] forState:UIControlStateNormal];
            }
        }
        [self.player play:[self.playListArray[indexPath.row] source]];
        [self changeViewWhenSongChange:indexPath.row];
        
        [request release];
    }
    else if([tableView isEqual:self.playTableView])
    {
        UIButton *btn = (UIButton *)[self.view viewWithTag:9000];
        if (indexPath.row == 0) {
            self.playModel = OrderModel;
            [btn setBackgroundImage:[UIImage imageNamed:@"Music_shunxu"] forState:UIControlStateNormal];
        }
        else if (indexPath.row == 1)
        {
            self.playModel = randomModel;
            [btn setBackgroundImage:[UIImage imageNamed:@"Music_suiji"] forState:UIControlStateNormal];
        }
        else
        {
            self.playModel = OneSongMode;
            [btn setBackgroundImage:[UIImage imageNamed:@"Music_danqu"] forState:UIControlStateNormal];
        }
        
    }
    else
    {
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MusicCollection"];
        NSArray *collecArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
        [self.player play:[collecArray[indexPath.row] source]];
                UIButton *collect = (UIButton *)[self.view viewWithTag:5000];
                [collect setBackgroundImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
        [self collectViewChange:indexPath.row];
        [self.playListView removeFromSuperview];
        
        [request release];
    }

    [UIView animateWithDuration:0.1 animations:^{
        self.tableView.frame = CGRectMake(0, self.view.frame.size.height , self.view.frame.size.width, 350 * kHeight);
        
        self.playTableView.frame = CGRectMake(10 * kWidth, self.view.frame.size.height, 120 * kWidth, 120 * kHeight);
        
        self.collectTableView.frame = CGRectMake(0, self.view.frame.size.height , self.view.frame.size.width, 350 * kHeight);
    }];
}

#pragma mark 创建播放模式页面
-(void)createPlayView
{
    self.playTableView = [[UITableView alloc]initWithFrame:CGRectMake(10 * kWidth, self.view.frame.size.height, 120 * kWidth, 120 * kHeight) style:UITableViewStylePlain];
    self.playTableView.dataSource = self;
    self.playTableView.delegate = self;
    self.playTableView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
    self.playTableView.showsVerticalScrollIndicator = YES;
    self.playTableView.scrollEnabled = NO;
    [self.view addSubview:self.playTableView];
    [_playTableView release];
    
    [self.playTableView registerClass:[MusicPlayModelTableViewCell class] forCellReuseIdentifier:@"MusicPlayModelTableViewCell"];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [UIView animateWithDuration:0.1 animations:^{
        self.tableView.frame = CGRectMake(0, self.view.frame.size.height , self.view.frame.size.width, 350 * kHeight);
        
        self.playTableView.frame = CGRectMake(10 * kWidth, self.view.frame.size.height, 120 * kWidth, 120 * kHeight);
        
        [self.playListView removeFromSuperview];
        
         self.collectTableView.frame = CGRectMake(0, self.view.frame.size.height , self.view.frame.size.width, 350 * kHeight);
        
    }];
}

#pragma mark 当歌曲改变时，改编页面
-(void)changeViewWhenSongChange:(NSInteger)row
{
   [self.imageview sd_setImageWithURL:[NSURL URLWithString:[self.playListArray[row] pic_750]] placeholderImage:[UIImage imageNamed:@"placeHoder"]];
    
    [self.image sd_setImageWithURL:[NSURL URLWithString:[self.playListArray[row] pic_750]] placeholderImage:[UIImage imageNamed:@"placeHoder"]];
  
    UIButton *btn = (UIButton *)[self.view viewWithTag:9002];
    [btn setBackgroundImage:[UIImage imageNamed:@"Music_kaishi"] forState:UIControlStateNormal];
    
    [self animationDidStart];
    [self animationResume];
    
    UILabel *songName = (UILabel *)[self.view viewWithTag:55555];
    songName.text = [self.playListArray[row] name];
    
    UILabel *singerName = (UILabel *)[self.view viewWithTag:66666];
    singerName.text = [[self.playListArray[row] User]objectForKey:@"name"];
    
}

-(void)collectViewChange:(NSInteger)row
{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"MusicCollection"];
    NSArray *collecArray = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    [self.imageview sd_setImageWithURL:[NSURL URLWithString:[collecArray[row] pic_750]] placeholderImage:[UIImage imageNamed:@"placeHoder"]];
    
    
    [self.image sd_setImageWithURL:[NSURL URLWithString:[collecArray[row] pic_750]] placeholderImage:[UIImage imageNamed:@"placeHoder"]];
    
    UIButton *btn = (UIButton *)[self.view viewWithTag:9002];
    [btn setBackgroundImage:[UIImage imageNamed:@"Music_kaishi"] forState:UIControlStateNormal];
    
    [self animationDidStart];
    [self animationResume];
    
    UILabel *songName = (UILabel *)[self.view viewWithTag:55555];
    songName.text = [collecArray[row] name];
    
    UILabel *singerName = (UILabel *)[self.view viewWithTag:66666];
    singerName.text = [collecArray[row] user];
    
    [request release];
}

#pragma mark 播放时间
//进度条
- (void)progressSliderAction:(UISlider *)sender{
    if (self.player) {
        //       把player的进度值给播放进度条
        [self.player seekToTime:sender.value];
    }
}

- (void)time{
    self.progressSlider.maximumValue = self.player.duration;
    self.progressSlider.value = self.player.progress;
    NSInteger proMin = (NSInteger)self.player.progress / 60;
    NSInteger proSec = (NSInteger)self.player.progress % 60;
    NSInteger durMin = (NSInteger)self.player.duration / 60;
    NSInteger durSec = (NSInteger)self.player.duration % 60;
    UILabel *begin = (UILabel *)[self.view viewWithTag:99999];
    begin.text = [NSString stringWithFormat:@"%02ld:%02ld", proMin, proSec];
    UILabel *all = (UILabel *)[self.view viewWithTag:100000];
    all.text = [NSString stringWithFormat:@"%02ld:%02ld", durMin, durSec];

    if (self.player.state == STKAudioPlayerStatePlaying && [begin.text isEqualToString:all.text]) {
        if (self.playModel == OrderModel) {
            if (self.row == self.playListArray.count - 1) {
                self.row = 0;
            }
            else
            {
                self.row = self.row + 1;
            }
            [self.player play:[self.playListArray[self.row] source]];
            [self viewWillAppear:YES];
            [self changeViewWhenSongChange:self.row];
        }
        else if(self.playModel == randomModel)
        {
            self.row = arc4random() % self.playListArray.count;
            [self.player play:[self.playListArray[self.row] source]];
        }
        else
        {
            [self.player play:[self.playListArray[self.row] source]];
        }
    }
}

#pragma mark 开始动画
-(void)animationDidStart
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.fromValue = [NSNumber numberWithFloat:0.0];
    animation.toValue = [NSNumber numberWithFloat:22 * M_PI];
    animation.duration = 100;
    animation.repeatCount = HUGE_VALF;
    //添加动画
    [self.image.layer addAnimation:animation forKey:@"rotation"];
    [self animationResume];
}

#pragma 暂停动画
- (void)animationStop
{
    CALayer *layer = self.image.layer;
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0;
    layer.timeOffset = pausedTime;
}
#pragma 继续动画
- (void)animationResume
{
    CALayer *layer = self.image.layer;
    CFTimeInterval pauseTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSince = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pauseTime;
    layer.beginTime = timeSince;
}

#pragma mark streamingKti代理方法
- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didStartPlayingQueueItemId:(NSObject *)queueItemId{
    NSLog(@"开始播放");
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState{
    NSLog(@"状态改变%u",previousState);
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didCancelQueuedItems:(NSArray *)queuedItems{
    NSLog(@"未知%@",queuedItems);
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject *)queueItemId{
    NSLog(@"完成加载");
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer logInfo:(NSString *)line{
    NSLog(@"信息%@",line);
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode{
    NSLog(@"%u错误",errorCode);
}

- (void)audioPlayer:(STKAudioPlayer *)audioPlayer didFinishPlayingQueueItemId:(NSObject *)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration{
    NSLog(@"结束播放");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
